//
//  GXBaseHandle.m
//  GaoXunTravel
//
//  Created by 杜梅 on 16/6/5.
//  Copyright © 2016年 May. All rights reserved.
//

#import "GXBaseHandle.h"
#import "NetWorkUtils.h"
#import "AppDelegate.h"
#import "GXUserModel.h"
#import "GXGetDeviceType.h"
#import <AFNetworking/AFNetworking.h>
@implementation GXBaseHandle

- (instancetype)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    NSLog(@"<<=============initWithBaseURL===============>>");
    
    self.requestSerializer = [AFJSONRequestSerializer serializer];
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    self.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",
                                                    @"text/json",
                                                    @"text/javascript",
                                                    @"text/html",
                                                    @"text/plain",nil];

    [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [self.requestSerializer setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"platform_version"];
    [self.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"platform"];
   
    [self.requestSerializer setValue:[GXGetDeviceType correspondVersion] forHTTPHeaderField:@"phone_info"];
    [self.requestSerializer setValue:SYS_VERSION forHTTPHeaderField:@"sysVersion"];
   
    [self.requestSerializer setValue:[GXUserModel shareInstance].UUIDString forHTTPHeaderField:@"uuid"];
    [self.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    self.requestSerializer.timeoutInterval = 10.0f;
    [self.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    /***  适配https  ****/
    self.securityPolicy.allowInvalidCertificates = YES;
    self.securityPolicy.validatesDomainName = NO;

    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    NSLog(@"=======HTTP request phone_info: %@", [GXGetDeviceType correspondVersion]);
    NSLog(@"=======HTTP request platform_version: %@", [[UIDevice currentDevice] systemVersion]);
    NSLog(@"======http request user_id: %@",[GXUserModel shareInstance].user_id);
    return self;
}

- (void)call:(ReqMethod)method URLString:(NSString *)URLString parameters:(id)parameters callback:(void (^)(GXResponse *))callback
{
    NSString *accessToken = [GXUserModel shareInstance].token ? [GXUserModel shareInstance].token : @"";
//    NSString * sessionid = [GXUserModel shareInstance].sessionid?[GXUserModel shareInstance].sessionid:@"";
    NSString * rcToken = [GXUserModel shareInstance].RCToken?[GXUserModel shareInstance].RCToken:@"";
    NSString * user_id = [GXUserModel shareInstance].user_id ?[GXUserModel shareInstance].user_id:@"";
    [self.requestSerializer setValue:user_id forHTTPHeaderField:@"user_id"];
//    [self.requestSerializer setValue:sessionid forHTTPHeaderField:@"sessionid"];
     [self.requestSerializer setValue:rcToken forHTTPHeaderField:@"token"];
    NSLog(@"=======HTTP request URL: %@", URLString);
    NSLog(@"=======HTTP request accessToken: %@", accessToken);
     NSLog(@"=======HTTP request params: %@", parameters);
     NSLog(@"=======HTTP request user_id: %@",[GXUserModel shareInstance].user_id);
    NSLog(@"======== http reqiuest sessionid :%@",[GXUserModel shareInstance].sessionid);
    switch (method) {
        case HTTPMethod_GET:
        {
            [self GET:URLString
           parameters:parameters progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
                  [self handleResponse:responseObject
                                 error:nil
                              callBack:callback];
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  [self handleResponse:nil
                                 error:error
                              callBack:callback];
              }];
            break;
        }
        case HTTPMethod_POST:
        {
            [self POST:URLString
            parameters:parameters progress:nil
               success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
                   [self handleResponse:responseObject
                                  error:nil
                               callBack:callback];
               } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                   [self handleResponse:nil
                                  error:error
                               callBack:callback];
               }];
            break;
        }
        default:
            break;
    }
}

- (void)callURLString:(NSString *)URLString
            ImageData:(NSData *)imageData
             callback:(void (^)(GXResponse *))callback
{
    [self POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData
                                    name:@"uploadFile"
                                fileName:@"myHeadUrl.jpg"
                                mimeType:@"image/jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self handleResponse:responseObject error:nil callBack:callback];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self handleResponse:nil error:error callBack:callback];
        
    }];
}


-(void)callurl:(NSString *)url  ImageArr:(NSArray *)imageArr callback:(void (^)(GXResponse *result))callback
{
    self.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",
                                                    @"text/json",
                                                    @"text/html",
                                                    nil];
    [self POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i =0; i<imageArr.count; i++) {
            UIImage *image = imageArr[i];
            NSData *data = UIImagePNGRepresentation(image);
            [formData appendPartWithFileData:data
                                        name:[NSString stringWithFormat:@"name[%d]",i+1]
                                    fileName:[NSString stringWithFormat:@"image%d.png",i+1]
                                    mimeType:@"image/png"];
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self handleResponse:responseObject error:nil callBack:callback];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self handleResponse:nil error:error callBack:callback];
        
    }];


}

- (void)handleResponse:(id)responseObject error:(NSError*)error callBack:(void(^)(GXResponse *result))callBack
{
    GXResponse *response = [GXResponse new];
    //    NSLog(@"========HTTP Code: %ld", (long)operation.response.statusCode);
    if (error) {
        NSLog(@"========HTTP error: %@", error);
        if ([error code] == NSURLErrorNotConnectedToInternet || [error code] == NSURLErrorTimedOut || [error code] == NSURLErrorCannotConnectToHost) {
            response.responseCode = 1020;
            response.responseContent = @"网络异常，请检查您的网络设置";
        }
        else
        {
            response.responseCode = [error code];
            response.responseContent = @"与服务器通讯失败，请稍后重试！";
        }
        response.isSuccess = NO;
    }
    else
    {
        NSInteger respCode = [[responseObject objectForKey:@"e"][@"code"]integerValue];
        
        NSString *respDesc =[responseObject objectForKey:@"e"][@"desc"];
        
        response.isSuccess = NO;
        
        if (respCode == 0) {
            response.isSuccess = YES;
        }

        response.responseCode = respCode;
        response.responseContent = respDesc;
        response.result = responseObject;
        
        NSLog(@"=======HTTP respCode: %ld , respDesc: %@", (long)respCode, respDesc);
        NSLog(@"=======HTTP result: %@", responseObject);
        
    }
    
    if (callBack) {
        callBack(response);
    }
}
@end
